import axios from "axios";
import httpurl from "./httpurl";
import { Toast, Dialog } from "vant";
// import { Message, MessageBox } from 'element-ui'
// import store from '@/store'
// import { getToken } from '@/utils/auth'

// create an axios instance
const service = axios.create({
  baseURL: httpurl, // api 的 base_url
  timeout: 50000 // request timeout
});

// request interceptor
service.interceptors.request.use(
  config => {
    // Do something before request is sent
    //todo 后期对接口的时候，把这个字段加上
    if (localStorage.getItem("loginToken")) {
      config.headers.common["Authorization"] = localStorage.getItem(
        "loginToken"
      );
    }
    return config;
  },
  error => {
    console.error("请求错误");
    // Do something with request error
    console.log(error); // for debug
    Promise.reject(error);
  }
);

// response interceptor
service.interceptors.response.use(
  response => {
    const res = response.data;
    //系统错误可以统一在这个里面处理
    // if (res.errno === 501) {
    //     Dialog.alert({
    //         message: '系统未登录，请重新登录'
    //     }).then(() => {
    //         // on close
    //     });
    //     return Promise.reject('error')
    // } else if (res.errno !== 0) {
    //     // 不属于系统错误属于业务错误，留给具体页面处理
    //     return Promise.reject(response)
    // } else {
    /* if(response.status==400){
                 Dialog.alert({
                     message: '系统未登录，请重新登录'
                 }).then(() => {
                     // on close
                 });
        } */
    return response.data;
    // }
  },
  error => {
    console.log("err" + error); // for debug
    Toast({
      message: "登录连接超时（后台不能连接，请联系系统管理员）",
      type: "error",
      duration: 5 * 1000
    });
    return Promise.reject(error);
  }
);

export default service;
